<template>
  <view class="person-box">
    <view class="header-common" :style="{ paddingTop: state.titleHeight + 3 + 'px' }">
      <view class="back-box" @tap="gotoBack">
        <image class="back-img" src="../../static/icon-back.png"></image>
      </view>
      <span>个人资料</span>
    </view>
    <view class="forms-box">
      <uni-forms
        ref="baseFormRef"
        :modelValue="state.baseFormData"
        :rules="state.customRules"
        label-width="120"
      >
       <div class="flex-forms">
          <uni-forms-item label="头像" name="headUrl" required>
						<button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
							<image :src="state.baseFormData.headUrl || 'https://model-capability.oss-cn-beijing.aliyuncs.com/pro/healthRun/avart-wu.png'"></image>
						</button> 
          </uni-forms-item>
        </div>
        <uni-forms-item label="姓名" name="customerName" required>
          <uni-easyinput
            v-model="state.baseFormData.customerName"
            :placeholderStyle="state.placeholderStyle"
            placeholder="请输入姓名"
          />
        </uni-forms-item>
        <uni-forms-item label="年龄" name="age" required>
          <uni-easyinput v-model="state.baseFormData.age" type="number" :placeholderStyle="state.placeholderStyle" placeholder="请输入年龄" />
        </uni-forms-item>
        <div class="flex-forms">
          <uni-forms-item label="性别" name="gender" required>
            <uni-data-checkbox
              selectedColor="#08CB8F"
              selectedTextColor="#FFFFFF"
              v-model="state.baseFormData.gender"
              mode="tag"
              :localdata="state.sexs"
            />
          </uni-forms-item>
        </div>
        <uni-forms-item label="身高 (cm)" name="height" required>
          <uni-easyinput
            type="number"
            v-model="state.baseFormData.height"
            :placeholderStyle="state.placeholderStyle"
            placeholder="请输入身高"
          />
        </uni-forms-item>
        <uni-forms-item label="体重 (kg)" name="weight" required>
          <uni-easyinput
            type="digit"
            v-model="state.baseFormData.weight"
            :placeholderStyle="state.placeholderStyle"
            placeholder="请输入体重"
          />
        </uni-forms-item>
        <uni-forms-item label="联系电话" name="emergencyContactMoblie" required>
          <uni-easyinput
            type="number"
            v-model="state.baseFormData.emergencyContactMoblie"
            :placeholderStyle="state.placeholderStyle"
            placeholder="请输入联系电话"
          />
        </uni-forms-item>
      </uni-forms>
    </view>
    <button class="confirm-btn" @tap="submit">确定</button>
  </view>
</template>

<script setup>
import { onLaunch, onLoad, onShow, onHide, onShareAppMessage, onShareTimeline } from "@dcloudio/uni-app";
import { reactive, ref, onMounted, getCurrentInstance } from "vue";
import * as API from "../../api/api";
import { storeToRefs } from "pinia";
import { userLoginStore } from "../../store/userLogin";
import { useShareStore } from "../../store/share";
import { useAppStore } from "../../store/app"
const useShareData = useShareStore()
const useAppData = useAppStore()
const userLoginData = userLoginStore();
const { proxy, ctx } = getCurrentInstance();
const regex = /^[1-9]\d*$/;

const state = reactive({
  isClick: true,
  userInfo: null,
  titleHeight: 0,
  baseFormData: {
    customerName: null,
    age: null,
    emergencyContactMoblie: "",
    gender: 1,
    weight: null,
    height: null,
		headUrl: "https://model-capability.oss-cn-beijing.aliyuncs.com/pro/healthRun/avart-wu.png"
  },
  sexs: [
    {
      text: "男",
      value: 1,
    },
    {
      text: "女",
      value: 2,
    },
  ],
  customRules: {
    customerName: {
      rules: [
        {
          required: true,
          errorMessage: "请实名填写，禁止使用敏感词汇，最长30字",
        },
        {
          validateFunction: function (rule, value, data, callback) {
            if (value.length > 30) {
              callback("请实名填写，禁止使用敏感词汇，最长30字")
            }
            return true
          }
        }
      ],
    },
    age: {
      rules: [
        {
          required: true,
          errorMessage: "请输入3到99岁实际年龄",
        },
        {
          validateFunction: function (rule, value, data, callback) {
            if (value.length > 2 ||  Number(value) < 3 || Number(value) > 99 || !regex.test(value)) {
              callback("请输入3到99岁实际年龄")
            }
            return true
          }
        }
      ],
    },
    gender: {
      rules: [
        {
          required: true,
          errorMessage: "性别不能为空",
        },
      ],
    },
    weight: {
      rules: [
        {
          required: true,
          errorMessage: "请输入15.00到150.99kg真实体重",
        },
        {
          validateFunction: function (rule, value, data, callback) {
            let parts = []
            const strNum = value.toString();
            if (value % 1 !== 0 || strNum.includes('.')) {
              parts = value.toString().split('.')
            } else {
              parts = [value]
            }
            if (Number(value) < 15 || Number(value) > 150.99 || (parts[1] && parts[1].length > 2) || (parts[0] && parts[0].length > 3) || value < 0) {
              callback('请输入15.00到150.99kg真实体重')
            }
            return true
          }
        }
      ],
    },
    height: {
      rules: [
        {
          required: true,
          errorMessage: "请输入100到300cm真实身高",
        },
        {
          validateFunction: function (rule, value, data, callback) {
            if (Number(value) < 100 || Number(value) > 300 || !regex.test(value)) {
              callback('请输入100到300cm真实身高')
            }
            return true
          }
        }
      ],
    },
    emergencyContactMoblie: {
      rules: [
        {
          required: true,
          errorMessage: "联系电话不能为空",
        },
        {
          validateFunction: function (rule, value, data, callback) {
            let iphoneReg = /^1[3-9]\d{9}$/
            if (!iphoneReg.test(value)) {
              callback('请输入正确的手机号')
            }
            return true
          }
        }
      ],
    },
  },
  placeholderStyle: "font-size: 16px;color: #ABAFBA;",
});

const baseFormRef = ref(null);

onShareAppMessage((res) => {
  return useShareData.shareInfo
})
onShareTimeline((res) => {
  return useShareData.shareInfo
})

const onChooseAvatar = (e) => {
	console.log("eee", e)
	uni.uploadFile({
		url: API.uploadFile, // 替换为你的服务器地址
		filePath: e.detail.avatarUrl,                       // 上传的文件路径
		name: 'file', // 后端接收文件的参数名
		formData: {
			// key: res.data.key,
			// policy: res.data.policy,
			// OSSAccessKeyId: res.data.accessId,
			// signature: res.data.signature,
			// success_action_status: "200",
			// 'x-oss-security-token': securityToken // 使用STS签名时必传。
		},
		success: (uploadFileRes) => {
			console.log('---上传成功:', JSON.parse(uploadFileRes.data).data)
			state.baseFormData.headUrl = JSON.parse(uploadFileRes.data).data
		},
		fail: (err) => {
			console.error('上传失败:', err)
		},
		complete: (uploadFileRes) => {
		}
	})
}

const gotoBack = () => {
  uni.navigateBack();
  state.isClick = true
};

const getTitleHeight = () => {
  let res = uni.getMenuButtonBoundingClientRect();
  state.titleHeight = res.top;
};
getTitleHeight();

const gotoChat = (url) => {
  uni.navigateTo({
    url: "/pages/chat/chat",
  });
};

const submit = () => {
  if (!state.isClick) return
  state.isClick = false
  state.baseFormData = {
    ...state.baseFormData,
    id: state.userInfo?.customers?.id,
    uuid: state.userInfo?.customers?.uuid,
    accountId: state.userInfo?.customers?.accountId,
    customerId: state.userInfo?.customers?.customerId,
  };
  baseFormRef.value
    .validate()
    .then((res) => {
      userLoginData
        .saveUserInfoData(state.baseFormData)
        .then((res) => {
          if (res.code === 0) {
            uni.showToast({
              title: "保存成功",
              icon: "none"
            })
            setTimeout(()=>{
              userLoginData.getUserInfoData(state.userInfo?.customers?.accountId).then(res => {
                gotoBack();
              });
            }, 1000)
          } else {
            state.isClick = true
          }
        })
        .catch((err) => {
          state.isClick = true
          console.log("保存失败");
        });
    })
    .catch((err) => {
      state.isClick = true
      console.log("err", err);
    });
};

onShow(() => {
  state.isClick = true
  state.userInfo = uni.getStorageSync("userInfo")
    ? JSON.parse(uni.getStorageSync("userInfo"))
    : null;
  state.baseFormData = state.userInfo?.customers;
	state.baseFormData.emergencyContactMoblie = state.baseFormData.emergencyContactMoblie ? state.baseFormData.emergencyContactMoblie : state.userInfo?.mobile;
});
onHide(() => {
  console.log("App Hide");
});
</script>

<style lang="scss" scoped>
.person-box {
  .confirm-btn {
    width: 686rpx;
    height: 88rpx;
    background: #08cb8f;
    border-radius: 44rpx;
    color: #fff;
    position: fixed;
    bottom: 24rpx;
    left: 50%;
    transform: translateX(-50%);
    z-index: 9;
  }
	.avatar-wrapper{
		width: 80rpx;
		height: 80rpx;
		padding: 0;
		border: none!important;
		background-color: #fff;
		&::after{
			border: none;
		}
		image{
			display: block;
			width: 80rpx;
			height: 80rpx;
		}
	}
  :deep(.uni-forms) {
    padding-bottom: 180rpx;
  }
  :deep(.uni-forms-item__label) {
    width: 60vw;
    font-size: 32rpx;
    color: #1c1c1e;
  }
  :deep(.uni-forms-item) {
    display: block;
    margin-bottom: 0rpx;
    padding: 32rpx 32rpx 24rpx;
    box-shadow: inset 0rpx -2rpx 0rpx 0rpx #e6e8ef;
  }
  :deep(.is-input-border) {
    border: none;
  }
  :deep(.uni-forms-item__error) {
    top: 140%;
  }
  .flex-forms {
    :deep(.uni-forms-item) {
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
    :deep(.uni-forms-item__label) {
      width: 200rpx;
    }
    :deep(.uni-forms-item__content) {
      flex: 0 1 auto;
    }
  }
  :deep(.uni-data-checklist) {
    .checklist-group{
      flex-wrap: nowrap !important;
    }
  }
}
</style>
